import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt


# 增加层数 inputs是输入数据，也就是每一个样本的规模，
def add_layer(inputs, in_size, out_size, activation_function=None):
    # insize行 outsize列 1 10
    with tf.name_scope('mylayer'):
        with tf.name_scope('myweights'):
            Weights = tf.Variable(tf.random_normal([in_size, out_size]), name='w')
        with tf.name_scope('mybiases'):
            # 1行outsize列，推荐不是0，在每一步骤训练中，都会有变化
            biases = tf.Variable(tf.zeros([1, out_size]) + 0.1, name='b')
        with tf.name_scope('myWx_plus_b'):
            # y=wx+b  1*in_size  insize*out_size   -->  1*outsize
            Wx_plus_b = tf.matmul(inputs, Weights) + biases
        if activation_function is None:
            outputs = Wx_plus_b
        else:
            outputs = activation_function(Wx_plus_b)
        return outputs


# ~~reshape([10,1]) 一个特性有300个例子
x_data = np.linspace(-1, 1, 300)[:, np.newaxis]
# 噪点，避免规整数据
noise = np.random.normal(0, 0.05, x_data.shape)
# y=x^2+b+噪点
y_data = np.square(x_data) - 0.5 + noise

# None 无论进来多少组例子都可以,dtype要定义
# name  x_input y_input
with tf.name_scope('myinputs'):
    xs = tf.placeholder(tf.float32, [None, 1], name='x_input')
    ys = tf.placeholder(tf.float32, [None, 1], name='y_input')

# 输入层1个神经元，因为输入数据就一个数字
# 隐藏层10个神经元
# 输出层一个神经元，因为输出数据就一个数字
L1 = add_layer(xs, 1, 10, activation_function=tf.nn.relu)
prediction = add_layer(L1, 10, 1, activation_function=None)

# 计算loss 误差
with tf.name_scope('myloss'):
    loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys - prediction), reduction_indices=[1]))

# 优化参数
with tf.name_scope('mytrain'):
    train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)

init = tf.global_variables_initializer()  # 替换成这样就好
sess = tf.Session()
# windows passed
# writer = tf.train.SummaryWriter("logs/",sess.graph)
sess.run(init)
#
# # 可视化
# fig = plt.figure()
# ax = fig.add_subplot(1, 1, 1)
# # 输入数据
# ax.scatter(x_data, y_data)
# # 可保留画布
# plt.ion()
# plt.show()
#
# for i in range(1000):
#     sess.run(train_step, feed_dict={xs: x_data, ys: y_data})
#     if i % 50 == 0:
#         # print(sess.run(loss, feed_dict={xs: x_data, ys: y_data}))
#         # try-catch模块
#         try:
#             ax.lines.remove(lines[0])
#         except Exception:
#             pass
#         prediction_value = sess.run(prediction, feed_dict={xs: x_data})
#         lines = ax.plot(x_data, prediction_value, 'r-', lw=5)
#         plt.pause(0.1)
